<template>
  <span @click="setCopy">
    |<span ml-10rpx text-26rpx>复制</span>
  </span>
</template>

<script setup lang="ts">

const props = defineProps({
  content: {
    type: String,
    default: "",
  },
});

function h5Copy(content: string) {
  if (!document.queryCommandSupported('copy')) {
    // 不支持
    return false
  }
  let textarea = document.createElement("textarea")
  textarea.value = content
  textarea.readOnly = true
  document.body.appendChild(textarea)
  textarea.select() // 选择对象
  textarea.setSelectionRange(0, content.length) //核心
  let result = document.execCommand("copy") // 执行浏览器复制命令
  textarea.remove()
  uni.showToast({
    title: "复制成功!",
    icon: "none"
  })
  return result

}
const setCopy = (text?: any) => {
  // #ifdef H5
  h5Copy(props.content || text)
  // #endif

  // #ifndef H5
  uni.setClipboardData({
    data: props.content || text,
    success: () => {
      uni.showToast({
        title: "复制成功!",
        duration: 3000,
        icon: "none",
      });
    },
    fail: (e) => {
      console.log(e)
      uni.showToast({
        title: "复制失败!" + e.errMsg,
        duration: 3000,
        icon: "none",
      });
    },
  });
  // #endif
};


defineExpose({
  setCopy
})
</script>

<style scoped lang="scss"></style>
